package com.shop.service;

import javax.mail.Message;

import javax.mail.Session;

import com.shop.dao.UserDao;
import com.shop.domain.User;
import com.shop.utils.MailUtil;

public class UserService {

	public void regist(User user) {
		try {
			//1.生成激活码
			String code = MailUtil.generateCode();
			user.setActivecode(code);
			
			//2.将用户信息保存到数据
			UserDao dao = new UserDao();
			dao.insert(user);
			
			//3.发送邮件s
			Session session = MailUtil.createSession();
			Message message = MailUtil.generateMessage(session, user);
			
			MailUtil.sendMail(message, session);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("发生邮件失败！");
		}
	}

	/**
	 * 帐户激活
	 * @param activecode
	 */
	public void active(String activecode) {
		UserDao dao = new UserDao();
		User user = dao.getUser(activecode);
		if (user == null) {
			throw new RuntimeException("激活码不存在！");
		}else{
			long curtime = System.currentTimeMillis();
			if ((curtime - user.getRegisttime().getTime()) > 1000 * 60 * 60 * 2 ) {
				//TODO 可以重发邮件，并更新激活码
				throw new RuntimeException("激活码已过期！");
			}else {
				//更新状态
				user.setActivecode(activecode);
				user.setState(1);
				dao.updateState(user);
			}
		}
	}

	public User login(User user) {
		User u = new UserDao().findUser(user.getUsername(), user.getPassword());
		return u;
	}

}
